import datetime
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, CheckConstraint
from sqlalchemy.orm import relationship

from app.db.base import Base

class Credit(Base):
    __tablename__ = "credits"

    user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
    balance = Column(Integer, default=0, nullable=False)

    __table_args__ = (CheckConstraint('balance >= 0', name='check_balance_positive'),)

    user = relationship("User", back_populates="credits")

class CreditLog(Base):
    __tablename__ = "credit_logs"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    amount = Column(Integer, nullable=False) # Positive for addition, negative for subtraction
    reason = Column(String, nullable=True)
    operator_id = Column(Integer, nullable=True) # Can be user ID (e.g., admin) or null for system actions
    created_at = Column(DateTime, default=datetime.datetime.now(datetime.timezone.utc))

    # Relationship to User (optional, if needed to easily query logs by user)
    # user = relationship("User") # Define back_populates in User if needed
